package com.wingscode.modules.app.controller;

import com.wingscode.common.utils.R;
import com.wingscode.common.validator.ValidatorUtils;
import com.wingscode.common.validator.group.AddGroup;
import com.wingscode.common.validator.group.UpdateGroup;
import com.wingscode.modules.common.entity.AgentEntity;
import com.wingscode.modules.common.service.AgentService;
import com.wingscode.modules.sys.controller.AbstractController;
import com.wingscode.modules.sys.entity.OfferPriceEntity;
import com.wingscode.modules.sys.service.OfferPriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 报价
 *
 * @author yan
 */
@RestController
@RequestMapping("/app/offerPrice")
public class OfferPriceController extends AbstractController {
	@Autowired
	private OfferPriceService offerPriceService;
	@Autowired
	private AgentService agentService;

	/**
	 * 保存报价信息
	 */
	@PostMapping("/save")
	public R save(@RequestBody OfferPriceEntity entity){
		if (entity.getUserId() == null)
			return R.error("userId为空");
		if (entity.getAgentId() == null)
			return R.error("agentId为空");

		// 获得当前企业信息
		AgentEntity agent = agentService.getById(entity.getAgentId());
		if (agent != null) {
			if (agent.getState() != 1)
				return R.error("企业审核未通过，暂时无法报价");
			if (agent.getIsOfferPrice() != 1)
				return R.error("升级成为渠道用户后可以进行报价");
		}

		entity.setCreateTime(new Date());
		entity.setState(0);
		ValidatorUtils.validateEntity(entity, AddGroup.class);

		offerPriceService.save(entity);

		return R.ok();
	}

	/**
	 * 修改报价信息
	 */
	@PostMapping("/update")
	public R update(@RequestBody OfferPriceEntity entity){
		// 获得当前企业信息
		AgentEntity agent = agentService.getById(entity.getAgentId());
		if (agent != null) {
			if (agent.getState() != 1)
				return R.error("企业审核未通过，暂时无法报价");
			if (agent.getIsOfferPrice() != 1)
				return R.error("升级成为渠道用户后可以进行报价");
		}

		entity.setUpdateTime(new Date());
		entity.setState(0);
		ValidatorUtils.validateEntity(entity, UpdateGroup.class);

		offerPriceService.updateById(entity);

		return R.ok();
	}

}
